Page({
  data: {
    order: null,
    messages: [],
    inputMsg: '',
    showOrderDetail: true,
    userId: null,
    orderId: null,
    lastMessageId: null
  },
  onLoad(options) {
    const { orderId, userId } = options;
    this.setData({ orderId, userId });
    this.loadOrderDetail(orderId);
  },
  onShow() {
    if (this.data.orderId) {
      this.loadMessages(this.data.orderId);
      this.timer = setInterval(() => {
        this.checkNewMessages(this.data.orderId);
      }, 10000);
    }
  },
  onHide() {
    clearInterval(this.timer);
  },
  onUnload() {
    clearInterval(this.timer);
  },
  async loadOrderDetail(orderId) {
    const app = getApp();
    try {
      const res = await app.request({
        url: `/api/orders/${orderId}`,
        method: 'GET'
      });
      this.setData({ order: res.data, showOrderDetail: true });
    } catch (e) {
      wx.showToast({ title: '订单详情加载失败', icon: 'none' });
    }
  },
  async loadMessages(orderId) {
    const userId = String(wx.getStorageSync('userId'));
    try {
      const res = await getApp().request({
        url: `/api/messages?orderId=${orderId}`,
        method: 'GET'
      });
      if (res.data) {
        const messages = res.data.map(msg => {
          const senderIdStr = String(msg.senderId);
          const isSelf = senderIdStr === userId;
          console.log('消息 senderId:', senderIdStr, '用户 id:', userId, 'isSelf:', isSelf, '内容:', msg.content);
          return {
            ...msg,
            isSelf,
            time: new Date(msg.createTime).toLocaleString()
          };
        });
        this.setData({ messages });
      }
    } catch (error) {
      wx.showToast({
        title: '加载消息失败',
        icon: 'none'
      });
    }
  },
  checkNewMessages(orderId) {
    const app = getApp();
    app.request({
      url: `/api/messages?orderId=${orderId}&lastId=${this.data.lastMessageId || 0}`,
      method: 'GET'
    }).then(res => {
      if (res.data && res.data.length > 0) {
        const newMessages = res.data;
        this.setData({
          messages: [...this.data.messages, ...newMessages],
          lastMessageId: newMessages[newMessages.length - 1].id
        });
      }
    }).catch(err => {
      console.error('检查新消息失败:', err);
    });
  },
  onInput(e) {
    this.setData({ inputMsg: e.detail.value });
  },
  async sendMsg() {
    const { inputMsg, orderId, userId, order } = this.data;
    if (!inputMsg.trim()) {
      wx.showToast({ title: '消息不能为空', icon: 'none' });
      return;
    }

    if (!order || !order.engineerId) {
      wx.showToast({ title: '订单信息不完整', icon: 'none' });
      return;
    }

    const app = getApp();
    try {
      const res = await app.request({
        url: '/api/messages',
        method: 'POST',
        data: {
          orderId,
          senderId: userId,
          receiverId: order.engineerId,
          content: inputMsg.trim()
        }
      });

      if (res.data && res.data.success) {
        this.setData({ inputMsg: '' });
        this.checkNewMessages(orderId);
      } else {
        wx.showToast({ 
          title: res.data?.error || '发送失败', 
          icon: 'none' 
        });
      }
    } catch (err) {
      console.error('发送消息失败:', err);
      wx.showToast({ 
        title: err.message || '发送失败', 
        icon: 'none' 
      });
    }
  },
  closeOrderDetail() {
    this.setData({ showOrderDetail: false });
  }
}); 